package com.yz.jdd.module.scan.view;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.google.zxing.Result;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.main.ChooseShopActivity;
import com.yz.jdd.module.main.MainActivity;
import com.yz.jdd.module.settings.SettingsActivity;
import com.yz.jdd.scan.ScanEventListener;
import com.yz.jdd.scan.SoftwareScanner;
import com.yz.jdd.scan.view.ViewfinderView;
import com.yz.jdd.webview.H5BridgeOtherActivity;
import com.yz.jdd.webview.Router;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;

import java.util.List;

public class ScanEvoucherActivity extends BaseActivity implements View.OnClickListener {
    TextView topBack;

    TextView topTitle;

    TextView topRight;

    SurfaceView previewView;

    ViewfinderView viewfinderView;

    private SoftwareScanner softwareScanner;

    TextView input_code;
    /**
     * 只能扫一次
     */
    private boolean isDecoded = true;

    String shopName;
    String shopId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isScan = true;
        super.onCreate(savedInstanceState);

        getCameraPermission();

    }


    private void getCameraPermission() {
        XXPermissions.with(ScanEvoucherActivity.this)
                //.constantRequest() //可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .permission(Permission.CAMERA
                ) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        LogUtils.e("=== noPermission: " + isAll);
                        dismissTopDialog();
                        //必要权限
                        if (granted.contains(Permission.CAMERA)) {
                            setContentView(R.layout.activity_scan_evoucher);

                            initView();
                            softwareScanner = SoftwareScanner.getInstance(ScanEvoucherActivity.this);
                            softwareScanner.init(previewView, viewfinderView);
                            toScan(true);

                        } else {
                            permissionDialog();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        LogUtils.e("=== noPermission: " + quick);
                        dismissTopDialog();
                        if (quick) {
                            showToast("被永久拒绝授权，请手动授予权限");
                            if (denied.contains(Permission.CAMERA)) {
                                permissionDialog();
                            }
                        } else {
                            ScanEvoucherActivity.this.finish();
                        }


                    }

                });
        if (!XXPermissions.isHasPermission(ScanEvoucherActivity.this, Permission.CAMERA)) {
            showTopDialog("为了您能正常使用【扫码支付】【设备绑定】功能，需向您申请相机权限。如果不允许，您将无法使用扫码功能。" +
                    "");
        }

    }

    //未授权权限弹出对话框
    public void permissionDialog() {
        final PublicDialog permission = new PublicDialog(ScanEvoucherActivity.this);
        permission.setTitle("请开启相关权限");
        permission.setMessage("为保证扫码功能正常使用，请务必开启相机权限!");
        permission.setRightBtn("去设置", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                XXPermissions.gotoPermissionSettings(ScanEvoucherActivity.this);
                permission.dismiss();
            }
        });
        permission.setLeftBtn("取消", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                permission.dismiss();
                ScanEvoucherActivity.this.finish();
            }
        });
        permission.setCancelable(false);
        permission.show();

    }

    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(this);
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        stopScanner();
    }

    @Override
    protected void onResume() {
        super.onResume();
        shopId = PreferencesUtils.getString(this, BaseConfigs.PREF_EVOUCHER_SHOPID);
        shopName = PreferencesUtils.getString(this, BaseConfigs.PREF_EVOUCHER_SHOPNAME);
        int shopNum = PreferencesUtils.getInt(this, BaseConfigs.PREF_EVOUCHER_SHOPNUM, 0);
        if (!TextUtils.isEmpty(shopName)) {
            topTitle.setText(shopName);
        }

        if (shopNum > 0) {
            topTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_keyboard_arrow_down_black_24dp, 0);
            topTitle.setOnClickListener(this);
        }

    }


    @Override
    protected void onDestroy() {

        SoftwareScanner.getInstance(this).release();
        super.onDestroy();
    }

    void initView() {
        topBack = findViewById(R.id.top_back);
        topBack.setVisibility(View.VISIBLE);
        topBack.setOnClickListener(this);
        topTitle = findViewById(R.id.top_title);

        previewView = findViewById(R.id.preview_view);
        viewfinderView = findViewById(R.id.viewfinder_view);
        viewfinderView.setText("请将取景器对准条形码/二维码");
        input_code = findViewById(R.id.input_code);
        input_code.setOnClickListener(this);

    }


    /**
     * 【重新扫码】
     */
    public void restartScanner() {

        if (softwareScanner.getCaptureHandler() != null) {
            softwareScanner.getCaptureHandler().sendEmptyMessage(R.id.restart_preview);
        }
    }

    /**
     * 停止扫码
     */
    public void stopScanner() {
        if (softwareScanner != null) {
            softwareScanner.stopScan();
        }
    }


    /**
     * UI线程初始化相机
     *
     * @param isScanable
     */
    private void toScan(final boolean isScanable) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (softwareScanner != null) {
                    softwareScanner.doScan(new ScanEventListener() {
                        @Override
                        public void onSuccess(Result result) {
                            if (result != null && isDecoded) {
                                isDecoded = false;
                                Router.startCancelVerifi(ScanEvoucherActivity.this, shopId, shopName, "1", result.getText());
                                finish();
                            }
                        }

                        @Override
                        public void onError() {

                            finish();
                        }
                    }, isScanable);
                }

            }
        });

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.top_back) {
            finish();
        } else {
            if (view.getId() == R.id.input_code) {
                Intent intent = new Intent(ScanEvoucherActivity.this, InputCodeActivity.class);

                startActivity(intent);
            } else {
                if (view.getId() == R.id.top_title) {
                    //打开门店选择
                    Intent intent = new Intent(new Intent(ScanEvoucherActivity.this, ChooseShopActivity.class));
                    intent.putExtra("from", "ScanEvoucherActivity");
                    intent.putExtra("shopId", shopId);
                    startActivityForResult(intent, Constants.SettingsActivityForResultCode);
                }
            }
        }
    }
}
